package com.amap.sign.impl;

import com.amap.constants.Constants;
import com.amap.exception.AmapException;
import com.amap.exception.AmapSignException;
import com.amap.sign.SignStrategy;
import com.amap.utils.SignUtils;
import org.springframework.stereotype.Service;
import java.nio.charset.StandardCharsets;
import java.security.*;
import java.security.spec.InvalidKeySpecException;
import java.security.spec.PKCS8EncodedKeySpec;
import java.util.Map;

/**
 * @author liuyi
 * @since 2025/10/31 11:15
 */
public class RSA2SignStrategy implements SignStrategy {
    @Override
    public String generateSign(Map<String, String> params, String merchantPrivateKey) throws AmapException {
        try {
            String signContent = SignUtils.buildSignContent(params);
            byte[] privateKeyBytes = SignUtils.decodeBase64(merchantPrivateKey);
            PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(privateKeyBytes);
            KeyFactory keyFactory = KeyFactory.getInstance(Constants.RSA_ALGORITHM);
            PrivateKey privateKey = keyFactory.generatePrivate(keySpec);
            Signature signature = Signature.getInstance(Constants.SIGN_ALGORITHM);
            signature.initSign(privateKey);
            signature.update(signContent.getBytes(StandardCharsets.UTF_8));
            byte[] signBytes = signature.sign();
            return SignUtils.encodeBase64(signBytes);
        } catch (NoSuchAlgorithmException | InvalidKeySpecException e) {
            throw new AmapSignException(Constants.ERROR_PRIVATE_KEY_INVALID, "商家私钥无效（格式错误或算法不支持）", e);
        } catch (SignatureException | InvalidKeyException e) {
            throw new AmapSignException(Constants.ERROR_SIGN_VERIFY_FAILED, "RSA2签名生成失败", e);
        }
    }
}
